import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    private int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            //向下调整 时间复杂度O(n)
            shiftDown(parent, usedSize);
        }
    }

    private void shiftDown(int parent, int usedSize) {
        int child = (2 * parent) + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            //child 一定是左右孩子最大的下标
            if(elem[child] > elem[parent]) {
                swap(parent, child);
            }else {
                //本身已经是大根堆了
                break;
            }
            parent = child;
            child = (2 * parent) + 1;
        }
    }

    private void swap(int i, int j) {
        int t = elem[i];
        elem[i] = elem[j];
        elem[j] = t;
    }

    public void offer(int value) {
        if(isFull()) {
            //扩容
            this.elem = Arrays.copyOf(elem, elem.length*2);
        }
        this.elem[usedSize] = value;

        //向上调整
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1)/2;
        while (child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public int poll() {
        int tmp = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
        return tmp;
    }

    public void heapSort() {
        int end = usedSize - 1;
        while (end > 0) {
            swap(0,end);
            shiftDown(0,end);
            end--;
        }
    }
}
